import { RocketChatClient } from '@rocket.chat/sdk/dist/client'
import process from 'node:process'

const {
  ROCKETCHAT_URL = 'http://localhost:3000',
  ROCKETCHAT_USER = 'admin',
  ROCKETCHAT_PASSWORD = 'admin',
} = process.env

class RocketChatService {
  private client: RocketChatClient

  constructor() {
    this.client = new RocketChatClient({
      host: ROCKETCHAT_URL,
      useSsl: ROCKETCHAT_URL.startsWith('https://'),
    })
  }

  async connect() {
    await this.client.login({
      username: ROCKETCHAT_USER,
      password: ROCKETCHAT_PASSWORD,
    })
  }

  async sendMessage(roomId: string, message: string) {
    return this.client.chat.postMessage({
      roomId,
      text: message,
    })
  }

  async createRoom(name: string, type: 'c' | 'p' = 'c') {
    return this.client.chat.createRoom({
      name,
      type,
    })
  }
}

export const rocketChatService = new RocketChatService()
